<?php
declare (strict_types = 1);

namespace app\controller;

use app\service\HouseService;
use app\service\OrderService;
use think\facade\Validate;
use think\Request;
use app\common\BaseController;

class OrderController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', 10) * 1;
      $start_date = $request->param('start_date', '');
      $end_date = $request->param('end_date', '');
      $customer = $request->param('customer', '');
      $model = $request->param('model', '');
      $js = $request->param('js', '');

      $conditions = [];
      if ($start_date) {
        $conditions[] = ['date', $start_date, '>='];
      }
      if ($end_date) {
        $conditions[] = ['date', $end_date, '<='];
      }
      if ($customer) {
        $customer = trim($customer);
        $conditions[] = ['customer', "%{$customer}%", 'like'];
      }
      if ($model) {
        $conditions[] = ['model', "%{$model}%", 'like'];
      }
      if ($js) {
        $conditions[] = ['js', $js, '='];
      }
      $order = [
        'date' => 'desc',
        'oid' => 'desc',
        'customer' => 'desc',
        'id' => 'desc'
      ];
      $res = OrderService::getInstance()->getAllOrder($conditions,$order);
      if ($customer || $model || $js) {
        $oids = array_unique(array_column($res, 'oid'));
        $res = OrderService::getInstance()->getAllOrder([['oid', $oids, 'IN']], $order);
      }
//      print_r($res);die;
      // 分组标识 oid
      // data：返回的数据
      $data = [];
      foreach ($res as $key => $item) {
        // 计算利润
        $item['profits'] = round(($item['tprice'] - ($item['cost'] * $item['amoumt'])), 2);
        // 添加到子数据
        if (!isset($data[$item['oid']])) {
          $data[$item['oid']] = [
            'id' => $item['id'],
            'order_id' => $item['oid'],
            'date' => $item['date'],
            'oid' => $item['oid'],
            'customer' => $item['customer'],
            'invoice' => $item['invoice'] ? '√' : '×',
            'tax' => $item['tax'] ? '√' : '×',
            'send' => $item['send'],
            'installtime' => $item['installtime'],
            'sendtime' => $item['sendtime'],
            'product' => '合计',
            'productn' => '-',
            'model' => '-',
            'price' => '-',
            'new' => '-',
            'js' => '-',
            'is_repayment' => 1,
            'cost' => 0,
            'npaid' => 0,
            'amoumt' => 0,
            'discount' => 0,
            'tprice' => 0,
            'profits' => 0,
            'paid' => 0
          ];
        }
        $data[$item['oid']]['children'][] = [
          'id' => $item['id'],
          'order_id' => $item['oid'],
          'date' => '',
          'oid' => '',
          'customer' => '',
          'invoice' => '',
          'tax' => '',
          'send' => '',
          'installtime' => '',
          'sendtime' => '',
          'product' => $item['product'],
          'productn' => $item['productn'],
          'model' => $item['model'],
          'price' => $item['price'],
          'cost' => $item['cost'],
          'npaid' => $item['npaid'],
          'amoumt' => $item['amoumt'],
          'discount' => $item['discount'],
          'tprice' => $item['tprice'],
          'profits' => $item['profits'],
          'paid' => $item['paid'],
          'new' => $item['new'] ? '新' : '旧',
          'js' => $item['js'],
          'is_repayment' => $item['is_repayment'],
          'resource' => $item['resource']
        ];
      }
      // 合计计算
      $list = [];
      $index = 1;
      foreach ($data as $value) {
        $value['index'] = $index++;
        $value['hasChildren'] = true;
        $value['color'] = 'yellow';
        // 子数据循环
        foreach ($value['children'] as &$child) {
          $value['cost'] += $child['cost'];
          $value['amoumt'] += $child['amoumt'];
          $value['discount'] += $child['discount'];
          $value['tprice'] += $child['tprice'];
          $value['profits'] += $child['profits'];
          $value['paid'] += $child['paid'];
          $value['npaid'] += $child['npaid'];
          $value['is_repayment'] = $value['is_repayment'] ? $child['is_repayment'] : 0;
          $child['index'] = $index++;
        }
        $list[] = $value;
      }
      // 分页
      $count = count($list); //总条数
      $start=($page-1) * $pageSize; //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalRecord' => $count * 1,
        'pageSize' => $pageSize * 1,
        'currPage' => $page * 1,
        'totalPage' => intval($count/$pageSize)+1
      ];
      $reList = array_slice($list,$start,$pageSize);
      return $this->send200ResponseWithPager($reList, $pager);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
      $data = $request->param('data', []);
      $validate = Validate::rule([
        'date' => 'require',
        'customer' => 'require',
        'address' => 'require',
        'cname' => 'require',
        'phone' => 'require',
        'product' => 'require',
        'productn' => 'require',
        'model' => 'require',
        'price' => 'require',
        'amoumt' => 'require',
        'js' => 'require'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $res = OrderService::getInstance()->createOrder($data);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
      $order = [
        'date' => 'desc',
        'oid' => 'desc',
        'customer' => 'desc',
        'id' => 'desc'
      ];
      $res = OrderService::getInstance()->getAllOrder([['oid', $id, '=']],$order);
      $data = [];
      foreach ($res as $key => $item) {
        // 添加到子数据
        if (!$data) {
          $data = [
            'order_id' => $item['oid'],
            'date' => $item['date'],
            'customer' => $item['customer'],
            'cname' => $item['cname'],
            'address' => $item['address'],
            'cname' => $item['cname'],
            'phone' => $item['phone'],
            'installtime' => $item['installtime'],
            'itime' => $item['itime'],
            'detail' => [],
            'invoice' => $item['invoice'],
            'tax' => $item['tax'],
            'ispw' => $item['ispw'],
            'total' => 0
          ];
        }
        $data['detail'][] = [
          'product' => $item['product'],
          'productn' => $item['productn'],
          'model' => $item['model'],
          'unit' => $item['unit'],
          'amoumt' => $item['amoumt'],
          'price' => $item['price'],
          'discount' => $item['discount'],
          'tprice' => $item['tprice'],
          'other' => $item['other'],
        ];
        $data['total'] += $item['tprice'];
      }
      return $this->send200Response($data);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
      $orderForm = $request->param('orderForm', []);
      $updateForm = $request->param('updateForm', []);
      $orderValid = Validate::rule([
        'date' => 'require',
        'customer' => 'require',
        'address' => 'require',
        'cname' => 'require',
        'phone' => 'require',
        'js' => 'require',
        'invoice' => 'require',
        'tax' => 'require',
        'ispw' => 'require'
      ]);
      $updateValid = Validate::rule([
        'price' => 'require',
        'discount' => 'require',
        'tprice' => 'require',
        'paid' => 'require'
      ]);
      // 判断订单数据
      if (!$orderValid->check($orderForm)) {
        return $this->send400Response($orderValid->getError());
      }
      // 判断数据
      if (!$updateValid->check($updateForm)) {
        return $this->send400Response($updateValid->getError());
      }
      $data = [
        'orderForm' => $orderForm,
        'updateForm' => $updateForm,
      ];
      $res = OrderService::getInstance()->updateOrder($id, $data);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
      $res = OrderService::getInstance()->deleteOrder($id);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

  /**
   * 通过oid获取订单数据
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function getByOid($oid)
  {
    $data = OrderService::getModel()
      ->where('oid', '=', $oid)
      ->select()
      ->toArray();
    $result = [];
    if (isset($data[0])) {
      $result = [
        'date' => $data[0]['date'],
        'new' => $data[0]['new'],
        'tax' => $data[0]['tax'],
        'invoice' => $data[0]['invoice'],
        'ispw' => $data[0]['ispw'],
        'customer' => $data[0]['customer'],
        'address' => $data[0]['address'],
        'cname' => $data[0]['cname'],
        'phone' => $data[0]['phone'],
        'installtime' => $data[0]['installtime'],
        'itime' => $data[0]['itime'],
        'js' => $data[0]['js'],
        'azf' => $data[0]['azf'],
        'details' => []
      ];
      foreach ($data as $value) {
        $result['details'][] = [
          'new' => intval($value['new']),
          'product' => $value['product'],
          'productn' => $value['productn'],
          'model' => $value['model'],
          'amoumt' => $value['amoumt'],
          'cost' => $value['cost'],
          'price' => $value['price'],
          'discount' => $value['discount'],
          'tprice' => $value['tprice'],
          'paid' => $value['paid'],
          'npaid' => $value['npaid'],
          'other' => $value['other'],
          'is_repayment' => $value['is_repayment']
        ];
      }
    }
    return $this->send200Response($result);
  }

  /**
   * 确认发货操作
   *
   * @return \think\Response
   */
  public function confirm(Request $request)
  {
    $oid = $request->param('oid', '');
    $res = OrderService::getInstance()->confirmOrder($oid);
    if (!$res['status']) {
      return $this->send400Response($res['msg']);
    }
    return $this->send200Response('ok');
  }

  /**
   * 撤销发货操作
   *
   * @return \think\Response
   */
  public function cancel(Request $request)
  {
    $oid = $request->param('oid', '');
    $res = OrderService::getInstance()->cancelOrder($oid);
    if (!$res['status']) {
      return $this->send400Response($res['msg']);
    }
    return $this->send200Response('ok');
  }

  /**
   * 获取单条数据详情
   */
  public function detail($id) {
    $data = OrderService::getModel()->find($id);
    return $this->send200Response($data);
  }

  /**
   * 确认还款
   *
   * @return \think\Response
   */
  public function repayConfirm(Request $request)
  {
    $id = $request->param('id', '');
    $oid = $request->param('oid', '');
    if (!$id && !$oid) {
      return $this->send400Response('缺少必要参数');
    }
    $res = OrderService::getInstance()->confirmRepayOrder($id, $oid);
    if (!$res['status']) {
      return $this->send400Response($res['msg']);
    }
    return $this->send200Response('ok');
  }

  /**
   * 撤销还款操作
   *
   * @return \think\Response
   */
  public function repayCancel(Request $request)
  {
    $id = $request->param('id', '');
    $oid = $request->param('oid', '');
    if (!$id && !$oid) {
      return $this->send400Response('缺少必要参数');
    }
    $res = OrderService::getInstance()->cancelRepayOrder($id, $oid);
    if (!$res['status']) {
      return $this->send400Response($res['msg']);
    }
    return $this->send200Response('ok');
  }

  /*
   * 获取某个订单的所有序列号
   */
  public function getOrderSerial($oid) {
    $res = OrderService::getInstance()->getOrderSerial($oid);
    if (!$res['status']) {
      return $this->send400Response($res['msg']);
    }
    return $this->send200Response($res['data']);
  }

  /*
   * 获取某个SKU的序列号
   */
  public function getSerial($id) {
    // 获取SKU详情
    $order_t = OrderService::getModel()::find($id);
    if ($order_t) {
      $order_t = $order_t->toArray();
    }
    $order_t['serial'] = OrderService::getInstance()->getSerialById($id);
    return $this->send200Response($order_t);
  }

  /*
  * 编辑序列号
  */
  public function updateSerial (Request $request, $id) {
    $data = $request->param('data', []);
    $res = OrderService::getInstance()->updateSerialById($id, $data);
    if (!$res['status']) {
      return $this->send400Response($res['msg']);
    }
    return $this->send200Response('ok');
  }
}